const Router = require('koa-router');
const {db, Op,QueryTypes } = require("../../models/db");
const {xe} = require("../../tools/tool");
const router = new Router();

// 计算订单详情
router.post('/zd/calOrder', async ctx => {
     let usr = ctx.user
     let tenantId = usr.tenantId;
     let cart = ctx.request.body.cart;
     if(cart.length === 0) return ctx.err('没有数据')
    let retsql = []
    cart.map(row => {
        retsql.push(` 
        select ${row.id} cartId, ${tenantId} tenantId, ${row.invId} invId,${usr.buId} buId,'${row.unit}' unit,${row.qty} qty,'${row.name}' name,'${row.unit1}' unit1,'${row.unit2}' unit2,${row.price} price,
        ${row.calNum} calNum,${row.deduction} deduction,${row.spec} spec 
         `)
    })
    let sqls = retsql.join(' union all ')
    let sstr = `select a.*,b.sendInvId,b.sendQty,b.buyQty,g.imgUrl from (${sqls}) a
    inner join v_goods g on a.tenantId=g.tenantId and a.invId=g.id 
    left join v_send_last b on a.tenantId=b.tenantId and a.invId=b.invId and a.buId=b.buId `
    let list = await db.query(sstr, {type: QueryTypes.SELECT})
    let goodsList = []
    let storage = await db.models['storage'].findOne({
        where: {
            tenantId,
            name: '默认仓库'
        }
    })
    for (let i = 0; i < list.length; i++) {
        let row = xe.clone(list[i]);
        goodsList.push({
            cartId: row.cartId,
            invId: row.invId,
            name: row.name,
            price: xe.toFixed(row.price,2),
            qty: row.qty,
            spec: row.spec,
            locationId: storage.id,
            locationName: storage.name,
            remark: row.remark,
            amount: xe.toFixed(xe.multiply(xe.subtract(row.price, row.deduction), row.qty), 2),
            calNum: row.calNum,
            unit: row.unit,
            unit1: row.unit1,
            unit2: row.unit2,
            imageUrl: row.imageUrl,
            deduction: row.deduction,
        })
        if(row.sendInvId) {
            if(row.sendInvId === row.invId) {
                let sendQty = row.sendQty
                let buyQty = row.buyQty
                let sends = xe.multiply(xe.divide(row.qty, buyQty), sendQty)
                let ds = xe.divide(Math.floor(xe.multiply(sends,row.spec)), row.spec)
                let qty = Math.floor(Math.floor(xe.multiply(sends,row.spec))/row.spec)

                if(xe.toNumber(qty) > 0) {
                    goodsList.push({
                        invId: row.invId,
                        name: row.name,
                        price: 0,
                        qty: qty,
                        spec: row.spec,
                        locationId: storage.id,
                        locationName: storage.name,
                        remark: `买${buyQty}赠${sendQty}`,
                        amount: 0,
                        calNum: row.calNum,
                        imageUrl: row.imageUrl,
                        unit: row.unit,
                        unit1: row.unit1,
                        unit2: row.unit2,
                        deduction: row.deduction,
                        send: '自赠'
                    })
                }
            }
            if(row.sendInvId !== row.invId) {
                let good = await db.models['goods'].findOne({
                    where: {
                        id: row.sendInvId,
                        tenantId
                    },
                })
                if(!good) return ctx.err('没找到赠品商品')
                let sendQty = row.sendQty
                let buyQty = row.buyQty
                let qty =  xe.multiply(xe.divide(row.qty, buyQty), sendQty)
                if(xe.toNumber(qty) > 0) {
                    let g = {
                        invId: row.sendInvId,
                        name: good.name,
                        price: 0,
                        qty:qty,
                        spec: good.spec,
                        locationId: storage.id,
                        locationName: storage.name,
                        remark: `买${buyQty}赠${sendQty}`,
                        amount: 0,
                        calNum: row.calNum,
                        unit: '',
                        unit1: good.unit1,
                        unit2: good.unit2,
                        imageUrl: good.imageUrl,
                        deduction: '',
                        send: '自赠'
                    }
                    if(row.calNum === 1) {
                        g.unit = good.unit2
                    }
                    else {
                        g.unit = good.unit1
                    }
                    goodsList.push(g)
                }
            }
        }
    }
    return ctx.suc('', {
        list: goodsList
    })
})

module.exports = router;
